<template>
  <div>
    <!--基本信息-->
    <div>
      <el-card class="box-cards">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
        </div>
        <el-form ref="form" :model="form" label-width="100px" size="small">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="采购单号" required>
                <el-input placeholder="系统自动生成" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购主题" required>
                <el-input v-model="form.procurementTopics" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购日期" required>
                <el-date-picker v-model="form.datePurchase" placeholder="请选择日期" style="width: 100%"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联采购申请">
                <el-select v-model="form.relevancy" placeholder="请选择" style="width: 495px" filterable allow-create
                  @change="currentStatusChange">
                  <el-option v-for="item in currentStatus" :key="item.index" :label="item.code"
                    :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购人员">
                <el-input v-model="form.purchasingStaff" placeholder="艾如波"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购部门">
                <el-input v-model="form.department" placeholder="采购部" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式">
                <el-input v-model="form.contact" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商">
                <el-select placeholder="请选择" v-model="form.vendor" style="width: 100%">
                  <el-option label="供应商1" value="供应商1"></el-option>
                  <el-option label="供应商2" value="供应商2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人">
                <el-input v-model="form.merchant" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式">
                <el-input v-model="form.contact2" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="期望到货日期">
                <el-date-picker v-model="form.arrival" placeholder="请选择日期" style="width: 495px"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="采购事由">
                <el-input v-model="form.affair" type="textarea" placeholder="请输入采购原因" cols="8" rows="4"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" cols="8" rows="4"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!--采购明细-->
    <div>
      <div>
        <el-card class="box-card2s">
          <div slot="header" class="clearfix">
            <span>采购明细</span>
          </div>
          <div>
            <el-button @click="addEquipment">添加</el-button>
            <el-button @click="removeSelected">移除</el-button>
          </div>
          <el-table :data="tableData" ref="registTable" style="width: 100%" stripe>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column label="序号" width="80" align="center" fixed>
              <template slot-scope="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="left" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="moveEquipment(scope.row)">移除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="设备编号" prop="numbering" align="center" width="180"></el-table-column>
            <el-table-column label="设备名称" prop="name" align="center"></el-table-column>
            <el-table-column label="规格型号" prop="model" align="center"></el-table-column>
            <el-table-column label="设备类型" prop="type" align="center"></el-table-column>
            <el-table-column label="品牌" prop="brand" align="center" width="150"></el-table-column>
            <el-table-column label="申请采购数量" prop="quantity" align="center" width="150"></el-table-column>
            <el-table-column label="参考单价" prop="reference" align="center" width="150"></el-table-column>
            <el-table-column label="实际购买数量" prop="actual" width="180" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.actual" :min="1" precision="2"
                  style="width: 150px"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="实际采购单价" prop="actualPrice" width="180" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.actualPrice" :min="1" style="width: 150px"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="金额" prop="amount">
              <template slot-scope="scope">
                {{ (scope.row.actual * scope.row.actualPrice).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" align="center" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 25px; margin-left: 940px;width: 100%;">
            <span>总数量：{{ totalQuantity }}</span>
            <span style="margin-left: 20px">总金额：{{ totalAmount.toFixed(2) }}</span>
          </div>
        </el-card>
      </div>
      <!--子设备选择框-->
      <el-dialog title="采购设备明细" :visible.sync="dialogVisible" width="60%">
        <div>
          <el-input placeholder="请输入设备编号/名称/规格型号" v-model="searchInput"
            style="width: 20%; margin-right: 10px"></el-input>
          <el-select placeholder="请选择设备类型" v-model="selectedType" style="width: 20%; margin-right: 10px">
            <el-option label="生产设备" value="生产设备"></el-option>
          </el-select>
          <el-input placeholder="请输入设备品牌" v-model="selectedDepartment"
            style="width: 20%; margin-right: 10px"></el-input>
          <el-button type="primary" @click="handleSearch2">查询</el-button>
          <el-button @click="handleReset2">重置</el-button>
        </div>
        <el-table size="mini" :cell-style="{ padding: '0px' }" :row-style="{ height: '35px' }" :data="filteredData"
          style="width: 100%; margin-top: 20px" stripe ref="registTable2">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column label="序号" width="50" align="center">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="numbering" label="设备编号" width="170" align="center"></el-table-column>
          <el-table-column prop="name" label="设备名称" align="center"></el-table-column>
          <el-table-column prop="model" label="规格型号" align="center"></el-table-column>
          <el-table-column prop="type" label="设备类型" align="center"></el-table-column>
          <el-table-column prop="brand" label="品牌" align="center"></el-table-column>
          <el-table-column prop="quantity" label="申请采购数量" align="center" width="180"></el-table-column>
          <el-table-column prop="reference" label="参考价格" align="center"></el-table-column>
          <el-table-column prop="estimate" label="预计总金额" align="center"></el-table-column>
        </el-table>
        <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size.sync="pageSize"
          :current-page.sync="currentPage" @current-change="handlePageChange2" style="margin-top: 20px" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </el-dialog>
    </div>

    <!--关联文件-->
    <div>
      <el-card class="box-card3s">
        <div slot="header" class="clearfix">
          <span>关联文件</span>
        </div>
        <el-button-group style="margin-bottom: 20px">
          <el-upload ref="upload2" action="http://localhost:9289/maintenance/upload2" :on-success="handleUploadSuccess2"
            :file-list="fileList" :auto-upload="true" :show-file-list="false" :before-upload="beforeUpload">
            <el-button type="primary">上传文档</el-button>
          </el-upload>
          <el-button @click="removeSelectedRows2">移除</el-button>
        </el-button-group>
        <el-table :data="documents" style="width: 100%" border @selection-change="handleSelectionChange37">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="name" label="文件名"></el-table-column>
          <el-table-column prop="uploadDate" label="上传时间"></el-table-column>
          <el-table-column prop="uploader" label="上传者"></el-table-column>
          <el-table-column prop="size" label="文档大小"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="removeRow2(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div style="height: 150px"></div>
    <el-footer class="footer">
      <el-button @click="handleCancel" style="margin-top: 20px; margin-left: -140px">关闭</el-button>
      <el-button type="primary" @click="handleConfirm2" style="margin-top: 20px; margin-left: 20px">确认</el-button>
    </el-footer>
  </div>
</template>

<script>
import {
  SelectApplicationAllQi,
  SelectOrderXi,
  SelectAll4
} from "@/api/eastjet-maintenance/caig/cai";
export default {
  data() {
    return {
      total: 0, // 分页总数
      pageSize: 10, // 每页显示条数
      currentPage: 1, // 当前页码
      //待采购申请单
      currentStatus: [],
      //表单上传
      form: {
        procurementTopics: "",
        datePurchase: "",
        relevancy: "",
        purchasingStaff: "",
        department: "",
        contact: "",
        vendor: "",
        merchant: "",
        contact2: "",
        arrival: "",
        affair: "",
        state: "1",
        remark: "",
        createdBy: this.$store.state.user.name,
        creationTime: new Date().toLocaleDateString('zh').replaceAll('/', '-'),
        tableData: [],
        documents: []
      },
      //关联文件上传
      documents: [],
      fileList: [],
      multipleSelection: [],
      // 数据属性可以在这里定义
      searchInput: "",
      selectedType: "",
      selectedDepartment: "",
      filteredData: [],
      dialogVisible: false,
      tableData: [],
      tableData2: [],
    };
  },
  computed: {
    totalQuantity() {
      return this.tableData.reduce(
        (sum, item) => sum + (item.actual || 0),
        0
      );
    },
    totalAmount() {
      return this.tableData.reduce(
        (sum, item) => sum + item.actualPrice * item.actual,
        0
      );
    },
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      SelectApplicationAllQi("7").then((res) => {
        this.currentStatus = res.data.data;
        this.form.currentStatus = res.data.data[0];
        SelectOrderXi(res.data.data[0].code).then((res) => {
          this.filteredData = res.data.data;
        });
      });
    },
    //申请采购单事件
    currentStatusChange(val) {
      SelectOrderXi(val).then((res) => {
        this.filteredData = res.data.data;
      });
    },
    handleSearch2() {
      // 实现搜索逻辑
    },
    handleReset2() {
      // 实现重置逻辑
      this.searchInput = "";
      this.selectedType = "";
      this.selectedDepartment = "";
    },
    handlePageChange2(page) {
      // 实现分页逻辑
      this.currentPage = page;
      // 这里可以添加获取分页数据的逻辑
    },
    handleSelectionChange37(selection) {
      this.multipleSelection = selection;
    },
    //上传文件大小判断
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return isLt10M;
    },
    //关联文件上传
    removeRow2(index) {
      this.childDevices.splice(index, 1);
    },
    removeSelectedRows2() {
      this.childDevices = this.childDevices.filter(
        (item) => !this.multipleSelection.includes(item)
      );
    },
    handleUploadSuccess2(response, file, fileList) {
      this.documents.push({
        name: file.name,
        url: file.url,
        uploadDate: new Date().toLocaleDateString('zh').replaceAll('/', '-'),
        uploader: this.$store.state.user.name,
        size: file.size + " KB",
      });
      console.log("数据2", this.documents);
    },
    handleConfirm() {
      // 处理确认操作
      this.tableData2 = this.$refs.registTable2.selection;
      // 处理确认操作
      if (this.tableData.length == 0) {
        for (let i = 0; i < this.tableData2.length; i++) {
          this.tableData.push({
            id: this.tableData2[i].id,
            numbering: this.tableData2[i].numbering,
            name: this.tableData2[i].name,
            model: this.tableData2[i].model,
            type: this.tableData2[i].type,
            brand: this.tableData2[i].brand,
            quantity: this.tableData2[i].quantity,
            reference: this.tableData2[i].reference,
            estimate: this.tableData2[i].estimate,
            actual: "",
            actualPrice: "",
            actualTotal: "",
            requestNumber: this.tableData2[i].requestNumber,
            remark: "",
            createdBy: this.$store.state.user.name,
            tombstone: 0,
          });
        }
      } else {
        for (let i = 0; i < this.tableData.length; i++) {
          for (let j = 0; j < this.tableData2.length; j++) {
            if (this.tableData[i].numbering == this.tableData2[j].numbering) {
              this.tableData[i].actual += 1;
              this.tableData2.splice(j, 1);
            }
          }
        }
        for (let i = 0; i < this.tableData2.length; i++) {
          this.tableData.push({
            id: this.tableData2[i].id,
            numbering: this.tableData2[i].numbering,
            name: this.tableData2[i].name,
            model: this.tableData2[i].model,
            type: this.tableData2[i].type,
            brand: this.tableData2[i].brand,
            quantity: this.tableData2[i].quantity,
            reference: this.tableData2[i].reference,
            estimate: this.tableData2[i].estimate,
            actual: "",
            actualPrice: "",
            actualTotal: "",
            requestNumber: this.tableData2[i].requestNumber,
            remark: "",
            createdBy: this.$store.state.user.name,
            tombstone: 0,
          });
        }
      }
      this.$refs.registTable2.clearSelection();
      this.dialogVisible = false;
    },
    //确认取消
    handleCancel() {
      this.$router.go(-1);
    },
    handleConfirm2() {
      this.form.tableData = this.tableData;
      this.form.documents = this.documents;
      SelectAll4(this.form).then((res) => {
        if (res.data.code == 520) {
          this.$router.go(-1);
          this.$notify({
            title: '成功',
            message: '这是一条成功的提示消息',
            type: 'success'
          });
        } else {
          this.$notify({
            title: '失败',
            message: '这是一条成功的提示消息',
            type: 'error'
          });
        }
      });
    },
    addEquipment() {
      // 新增设备的逻辑
      this.dialogVisible = true;
    },
    moveEquipment(row) {
      // 移除Equipment的逻辑
      const index = this.tableData.indexOf(row);
      if (index > -1) {
        this.tableData.splice(index, 1);
      }
    },
    removeSelected() {
      // 根据选中项移除设备的逻辑
      const selected = this.$refs.registTable.selection;
      console.log("数据", selected);
      this.tableData = this.tableData.filter(
        (item) => !selected.includes(item)
      );
    }
  }
};
</script>

<style scoped>
/* 样式可以在这里定义 */
.fixed-footer-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.footer {
  text-align: center;
  background-color: #eeeded;
  position: fixed;
  bottom: 0;
  z-index: 12;
  width: 100%;
}

.app-container {
  width: 1300px;
  /* height: 1000px; */
}

.box-cards {
  width: 1254px;
  margin-left: 30px;
  margin-top: 20px;
  height: 640px;
}

.box-card2s {
  width: 1254px;
  margin-left: 30px;
  margin-top: 20px;
}

.box-card3s {
  width: 1254px;
  margin-left: 30px;
  margin-top: 20px;
}
</style>
